package com.test.exception;

import com.auth0.jwt.exceptions.*;
import com.test.entity.JsonResult;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//这个类目前没用，用的是自己封装的全局异常
@RestControllerAdvice
public class GlobalExceptionHandling {
    /**
     * 处理shiro框架异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ShiroException.class)
    public JsonResult doHandleShiroException(
            ShiroException e) {
        JsonResult r = new JsonResult();
        r.setState(0);
        if (e instanceof UnknownAccountException) {
            r.setMessage("账户不存在~~");
        } else if (e instanceof LockedAccountException) {
            r.setMessage("账户已被禁用");
        } else if (e instanceof IncorrectCredentialsException) {
            r.setMessage("密码不正确");
        } else if (e instanceof AuthorizationException) {
            r.setMessage("没有此操作权限");
        } else {
            r.setMessage("系统维护中");
        }
        e.printStackTrace();
        return r;
    }

    @ExceptionHandler(JWTVerificationException.class)
    public JsonResult doJwtError(JWTVerificationException jwtException) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(000);
        if (jwtException instanceof SignatureVerificationException) {
            jsonResult.setMessage("签名不一致异常");
        } else if (jwtException instanceof TokenExpiredException) {
            jsonResult.setMessage("令牌过期异常");
        } else if (jwtException instanceof AlgorithmMismatchException) {
            jsonResult.setMessage("算法不匹配异常");

        } else if (jwtException instanceof InvalidClaimException) {
            jsonResult.setMessage("失效的payload异常");
        } else
            jsonResult.setMessage("token无效");

        return jsonResult;
    }

    //定义全局异常处理
    @ExceptionHandler(value = RuntimeException.class)
    public JsonResult topException(RuntimeException e) {
        e.printStackTrace();
        return new JsonResult(0, e.getMessage());
    }

}